package edu.yngsxy.wkstudy.core.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * WkRedisService
 */
@Component
public class WkRedisService {

    private final StringRedisTemplate redisTemplate;
    private static final int SCAN_BATCH_SIZE = 100;

    @Autowired
    public WkRedisService(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
    /**
     * 使用SCAN命令安全地根据模式删除键
     */
    public long deleteKeysByPattern(String pattern) {
        long deleteCount = 0;
        List<String> keysToDelete = new ArrayList<>(SCAN_BATCH_SIZE);

        ScanOptions scanOptions = ScanOptions.scanOptions()
                .match(pattern)
                .count(SCAN_BATCH_SIZE)
                .build();

        try (Cursor<String> cursor = redisTemplate.scan(scanOptions)) {
            while (cursor.hasNext()) {
                String key = cursor.next();
                keysToDelete.add(key);

                if (keysToDelete.size() >= SCAN_BATCH_SIZE) {
                    deleteCount += redisTemplate.delete(keysToDelete);
                    keysToDelete.clear();
                }
            }

            if (!keysToDelete.isEmpty()) {
                deleteCount += redisTemplate.delete(keysToDelete);
            }

        } catch (Exception e) {
            throw new RuntimeException("SCAN删除操作出错", e);
        }

        return deleteCount;
    }

    /**
     * 使用SCAN命令查找匹配的键（不删除）
     *
     * @return
     */

    public Set<String> findKeysByPattern(String pattern) {
        ScanOptions scanOptions = ScanOptions.scanOptions()
                .match(pattern)
                .count(SCAN_BATCH_SIZE)
                .build();

        return redisTemplate.execute(connection -> {
            Set<String> keys = new HashSet<>();

            // 使用新的API：connection.keyCommands().scan()
            try (Cursor<byte[]> cursor = connection.keyCommands().scan(scanOptions)) {
                while (cursor.hasNext()) {
                    byte[] keyBytes = cursor.next();
                    keys.add(new String(keyBytes, StandardCharsets.UTF_8));
                }
            }

            return keys;
        }, true);
    }
    /**
     * 统计匹配模式的键数量
     */
    public long countKeysByPattern(String pattern) {
        Set<String> keys = findKeysByPattern(pattern);
        return keys != null ? keys.size() : 0;
    }
}
